package org.jctc.els.modules.biz.controller.projects;

import com.xkcoding.http.support.Http;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jctc.els.common.config.BladeFileConfiguration;
import org.jctc.els.modules.biz.excel.ElsReportGouzhiJfysExcel;
import org.jctc.els.modules.biz.excel.ElsReportKaifaWwfysmxExcel;
import org.jctc.els.modules.biz.excel.PurchaseProjectsExcel;
import org.jctc.els.modules.biz.service.IElsProjectReportExploitService;
import org.jctc.els.modules.biz.service.projects.IElsProjectReportGouzhiService;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.excel.util.ExcelUtil;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.tenant.annotation.NonDS;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "项目可研报告导入")
@RestController
@RequestMapping("/elsProjectsReport")
@NonDS
@ApiIgnore
@AllArgsConstructor
@MultipartConfig
public class ElsProjectReportController extends BladeController {

    @Autowired
    IElsProjectReportGouzhiService gouzhiService;

    @Autowired
    BladeFileConfiguration bladeFileConfiguration;

    @Autowired
    IElsProjectReportExploitService exploitService;

    @GetMapping("/jfys")
    public R jfys(@RequestParam("id")String id){
        return R.data(gouzhiService.getJfysId(id));
    }

    @GetMapping("/wwfysmx")
    public R wwfysmx(@RequestParam("id")String id){
        return R.data(exploitService.getWwfysmxId(id));
    }

    @GetMapping("/els-project-report-gouzhi-exprot")
    public void gouzhiExprot(HttpServletResponse response){
        List<ElsReportGouzhiJfysExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "培训购置经费模板", "培训购置经费模板数据表", list, ElsReportGouzhiJfysExcel.class);
    }

    @GetMapping("/els-project-report-kaifa-exprot")
    public void kaifaExprot(HttpServletResponse response){
        List<ElsReportKaifaWwfysmxExcel> list = new ArrayList<>();
        ExcelUtil.export(response, "培训开发预算明细模板", "培训开发预算明细数据表", list, ElsReportKaifaWwfysmxExcel.class);
    }

    /**
     * 导入培训购置可研报告数据
     */
    @PostMapping("/els-project-report-gouzhi")
    @ApiOperation(value = "导入培训购置", notes = "传入excel")
    public R importPurchaseProjects(HttpServletRequest request,String gouZhiId) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        return gouzhiService.importPurchaseProjects(multipartFile, request,gouZhiId);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }

    /**
     * 导入培训购置可研报告数据
     */
    @PostMapping("/els-project-report-kaifa")
    @ApiOperation(value = "导入培训开发", notes = "传入excel")
    public R kaifaReport(HttpServletRequest request,String gouZhiId) {
        String fileName = "";
        //创建一个“硬盘文件条目工厂”对象
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //设置阈值，设置JVM一次能够处理的文件大小（默认吞吐量是10KB）
        factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD);
        //设置临时文件的存储位置（文件大小大于吞吐量的话就必须设置这个值，比如文件大小：1GB ，一次吞吐量：1MB）
        factory.setRepository(new File(bladeFileConfiguration.getUploadPath()));
        //创建核心对象
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        //设置最大可支持的文件大小（10MB）
        fileUpload.setFileSizeMax(1024 * 1024 * 50);
        //设置转换时使用的字符集
        fileUpload.setHeaderEncoding("UTF-8");
        if (ServletFileUpload.isMultipartContent(request)) {
            try {
                List<FileItem> fileItems = fileUpload.parseRequest(request);
                for (FileItem fileItem : fileItems) {
                    if (fileItem.isFormField()) {//判断该FileItem为一个普通的form元素
                        //获取字段名
                        String fieldName = fileItem.getFieldName();
                        //获取字段值，并解决乱码
                        String fieldValue = fileItem.getString("UTF-8");
                        System.out.println(fieldName + " : " + fieldValue);

                    } else {//判断该FileItem为一个文件

                        System.out.println("Start to upload file!");
                        //获取文件名
                        fileName = fileItem.getName();
                        System.out.println("fileName : " + fileName);
                        //获取文件大小
                        long fileSize = fileItem.getSize();
                        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
                        return exploitService.importPurchaseProjects(multipartFile, request,gouZhiId);
                        //fileItem.write(new File(bladeFileConfiguration.getUploadPath() + File.separator + fileName));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                return R.fail(e.getMessage());
            }
        }
        return R.success("导入成功");
    }


}
